package com.example.springboot159.util;

import com.example.springboot159.controller.demo.TestControlelr;
import org.springframework.web.bind.annotation.RestController;

import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class ToolUtils {
    //判断指定类型的注释存在于此元素上,
    public static boolean isAnnotated(AnnotatedElement element, Class<? extends Annotation> annotationType) {
        return element.isAnnotationPresent(annotationType);
    }

    public static <C extends Annotation> C findAnnotation(AnnotatedElement element, Class<C> annotionType) {
        C annotation = element.getAnnotation(annotionType);
        return annotation;
    }

    public static Set<Field> getAllFields(Class<?> type){
        Set<Field> resultSet = new HashSet<>(32);
        if (type != null && !type.equals(Object.class)){
            for (Class<?> object:getAllSuperTypes(type)){
                resultSet.addAll(Arrays.asList(object.getDeclaredFields()));
            }
        }
        return resultSet;
    }

    /**
     * 拿到该类实现的接口和继承的父类
     * @param type
     * @return
     */
    public static Set<Class<?>> getSuperTypes(final Class<?> type) {
        Set<Class<?>> resultSet = new HashSet<>(32);

        Class<?> superClass = type.getSuperclass();
        Class<?>[] interfaces = type.getInterfaces();
        if (superClass != null && !superClass.equals(Object.class)) resultSet.add(superClass);
        if (interfaces != null && interfaces.length > 0) resultSet.addAll(Arrays.asList(interfaces));
        return resultSet;
    }

    /**
     * 获取所有实现的接口和继承的父类
     * @param type
     * @return
     */
    public static Set<Class<?>> getAllSuperTypes(final Class<?> type) {
        Set<Class<?>> resultSet = new HashSet<>(32);
        if (type != null && !type.equals(Object.class)) {
            resultSet.add(type);
            for (Class<?> superType : getSuperTypes(type)) {
                resultSet.addAll(getAllSuperTypes(superType));
            }
        }
        return resultSet;
    }

    public static void main(String[] args) {
        System.out.println(ToolUtils.isAnnotated(TestControlelr.class, RestController.class));
    }
}
